package com.example.web.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.example.api.entity.User;
import com.example.api.service.DatabaseInfoService;
@Controller
public class LoginController {

	@Autowired
	private DatabaseInfoService databaseInfoService;
	
	@RequestMapping({"/","index.html"})
	public String index() {
		return "login";
	}
	
	@PostMapping("/login")
	public String login(String username,String password,
			Map<String,Object>map,HttpSession session) {
		
		if(!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
			User user=databaseInfoService.getUserInfoByLoginInfo(username, password);
			if(user!=null) {
				session.setAttribute("userId", user.getId());
				session.setAttribute("username", username);
				return "redirect:page/mainPage";
			}else {
				map.put("msg", "用户名或密码错误");
				return "login";
			}
		}else {
			map.put("msg", "用户名或密码错误");
			return "login";
		}
	}
	
	@RequestMapping(value="/logout")
	public String logout(HttpServletRequest request){
		ModelAndView result = new ModelAndView("login");
		HttpSession session = request.getSession();//获取当前session
		if(session!=null){
			//User user = (User)session.getAttribute("yh");//从当前session中获取用户信息
			session.invalidate();//关闭session
		}
		return "redirect:/";
		
	}
	
	
}
